package cn.wyj.controller;

import cn.wyj.domain.ArticleResponseData;
import cn.wyj.domain.Comment;
import cn.wyj.service.CommentService;
import cn.wyj.utils.MyUtils;
import com.vdurmont.emoji.EmojiParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Controller
public class CommentController  {
    @Autowired
    private CommentService commentService;

    @PostMapping("/comments/publish")
    @ResponseBody
    public ArticleResponseData pushComment(HttpServletRequest request, @RequestParam Integer aid,@RequestParam String text){
        //去除js脚本
        text= MyUtils.cleanXSS(text);
        text = EmojiParser.parseToAliases(text);
        //获取当前登录用户
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //封装评论信息
        Comment comment = new Comment();
        comment.setArticleId(aid);
        comment.setAuthor(user.getUsername());
        comment.setCreated(new Date());
        comment.setContent(text);
        comment.setIp(request.getRemoteAddr());
        try {
            commentService.addComment(comment);
            return ArticleResponseData.ok();
        }catch (Exception e){
            return ArticleResponseData.fail();
        }


    }

}
